#include <iostream>
#include <string>
#include <queue>
#include <unordered_map>

using namespace std;

unordered_map<string, int> dist;
string s;
string ans = "123804765";
int dx[] = { 0,0,-1,1 };
int dy[] = { 1,-1,0,0 };

void bfs()
{
	queue<string> q;
	q.push(s);
	dist[s] = 0;
	while (q.size())
	{
		auto t = q.front(); q.pop();
		int pos = 0;
		while (t[pos] != '0') pos++;
		int i = pos / 3, j = pos % 3;
		for (int k = 0; k < 4; k++)
		{
			
			int x = i + dx[k], y = j + dy[k];
			if (x >= 0 && x <= 2 && y >= 0 && y <= 2)
			{
				string next = t;
				int p = x * 3 + y;
				swap(next[p], next[pos]);
				if (dist.count(next)) continue;

				dist[next] = dist[t] + 1;
				q.push(next);
				if (next == ans) return;
			}
		}
	}
}




int main()
{
	cin >> s;

	bfs();

	cout << dist[ans] << endl;
	return 0;
}